//主页--天气预警代码
function weatherManager() {
	// 主页上的panel div，在index.xhtml中
	var divId = 'affectObjDiv';
	//panel
	var protectUtil = new ProtectionStatusEvaluation();

	var weatherPop = null;
	var currentPanel = '';

	this.show = function() {
		clearAll();
		initMapData();
		showTable();
		initTableData();
	};

	this.onPanelClick = function(title) {
		protectUtil.removePoints();
		if (currentPanel != title) {
			currentPanel = title;
		} else {
			currentPanel = '';
		}
		if (currentPanel == '保护状态评估') {
			protectUtil.drawPoints();
		}
	};
	/**
	 * 打开气象预警分析界面
	 */
	this.openWeatherInfoWin = function(wobj) {
		var lonlat = new SuperMap.LonLat(wobj.lon, wobj.lat);
		checkPosition(lonlat);
		var url = "/ui/map/dialog/weatherAlarmDialog.xhtml?weatherWarningId="
				+ wobj.id;
		if (weatherPop) {
			weatherPop.remove();
		}
		weatherPop = new Popup(wobj.lon, wobj.lat);
		weatherPop.showHoverEffect(false);
		weatherPop.setTitle("<div style='width:250px;'>" + wobj.title
				+ "</div>");
		weatherPop.setRowContent("<div style='width:250px;'>" + wobj.des
				+ "</div>");
		var btn = "<div style='height:37px;width:250px;'><a href='javascript:void(0)' onclick='MyModal.showModal(\""
				+ url
				+ "\",null,null,\""
				+ wobj.title
				+ "\")' class='btn btn-sm btn-info btn-flat pull-left'>预警分析</a><div>";
		weatherPop.setRowContent(btn).setAutoSize(true).showCloseIcon(true)
				.showRowOverflow(false);
		weatherPop.show();
	};

	this.openDialog = function(start, end) {
		var url = '/ui/map/weatherWarnDetail.xhtml?start='
				+ start + '&end=' + end;
		MyModal.showModal(url, null, null, "气象预警明细");

	};

	/**
	 * 地图数据更新
	 */
	function initMapData() {
		$.getJSON("/rest/getWeatherWarningMapData", function(result) {
			drawWeatherMap(result);
		});
	}
	;

	/**
	 * table数据更新
	 */
	function initTableData() {
		$.getJSON("/rest/getWeatherWarningTableData", function(result) {
			var faultData = result.warningEquipments;
			var secondaryData = result.secondaryStatus;
			initTable(faultData, secondaryData);
		});
	}
	/**
	 * 加载table
	 */
	function initTableDataset(faultData) {
		var dataset = [];
		var dsmap = new Map();
		for ( var i in faultData) {
			var f = faultData[i];
			dsmap.put(f.type, f.data);
		}
		// 为了进行排序
		var types = [ '雷电', '雷电事件', '暴雨', '暴雨事件', '台风', '台风事件', '森林火险',
				'森林火险事件', '暴雪', '暴雪事件' ];
		for ( var i in types) {
			var ds = dsmap.get(types[i]);
			if (ds) {
				dsmap.remove(types[i]);
				ds.sort(sortDs);
				dataset.push({
					type : types[i],
					data : ds
				});
			}
		}
		dsmap.each(function(index, key, value) {
			value.sort(sortDs);
			dataset.push({
				type : key,
				data : value
			});
		});
		return dataset;
	}

	/**
	 * 查询div的组装、添加查询时间等
	 */
	var queryDiv = (function() {
		var component, restore, query, error, minus, start, end;
		var pattern = 'yyyy-MM-dd';
		function getComponent() {
			component = $('<div class="panel-collapse collapse in" style="background:white" />');
			var now = new Date();
			var last = new Date(now.getTime() - 86400000);//一天前的时间戳
			var d = $('<div style="display:flex;"/>').appendTo(component);
			minus = $(
					'<span class="btn btn-default" ><i class="fa fa-arrow-left"></i></span>')
					.appendTo(d);
			start = $(
					'<input type="text" class="form-control thunder-warning-start"/>')
					.appendTo(d);
			end = $(
					'<input type="text" class="form-control thunder-warning-end"/>')
					.appendTo(d);
			// restore = $('<span class="btn btn-default" ><i class="fa
			// fa-repeat"></i></span>').appendTo(d);
			query = $('<span class="btn btn-default" >搜索</span>').appendTo(d);

			start.val(DateUtil.pattern(last, pattern));
			end.val(DateUtil.pattern(now, pattern));
			addListener();
			// start.val('2018-03-12 00:00');
			// end.val('2018-03-15 00:00');
			return component;
		}
		function addListener() {
			var now = new Date();
			var last = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
			var startTime = DateUtil.pattern(last, pattern);
			var endTime = DateUtil.pattern(now, pattern);
			minus.click(function() {
				var str = start.val();
				var d = new Date(str);
				d.setTime(d.getTime() - 24 * 3600 * 1000);
				start.val(DateUtil.pattern(d, pattern));
			});
			query.click(function() {
				// 将空的和不对的补齐
				var sta = start.val();
				var s = new Date(sta);
				if (!sta || s.toString() == 'Invalid Date') {
					sta = startTime;
					$('.thunder-warning-start').val(startTime);
					s = new Date(sta);
				}
				var en = $('.thunder-warning-end').val();
				var e = new Date(en);
				if (!en || e.toString() == 'Invalid Date') {
					en = endTime;
					$('.thunder-warning-end').val(endTime);
					e = new Date(en);
				}
				// 判断是否在允许范围内
				startTime = sta;
				endTime = en;
				weatherMan.openDialog(startTime, endTime);
			});
			start.datetimepicker({
				format : 'yyyy-mm-dd',
				minView : 2,
				autoclose : true,
				endDate : new Date(),
				todayHighlight : true,
			});
			end.datetimepicker({
				format : 'yyyy-mm-dd',
				minView : 2,
				autoclose : true,
				endDate : new Date(),
				todayHighlight : true,
				pickerPosition : 'bottom-left',
			});
		}
		function getQueryTime() {
			return [ start.val(), end.val() ];
		}
		return {
			getComponent : getComponent,
			addListener : addListener,
			getQueryTime : getQueryTime
		};
	})();

	//排序
	function sortDs(obj1, obj2) {
		var c1 = obj1[2];
		var c2 = obj2[2];
		if (c1 && c2 && c1 > 0 && c2 > 0) {
			return c2 - c1;
		} else if (c1 && c1 > 0) {
			return -1;
		} else if (c2 && c2 > 0) {
			return 1;
		} else {
			var n1 = obj1[1];
			var n2 = obj2[1];
			var t1 = n1 ? (n1 == '' ? 0 : 1) : 0;
			var t2 = n2 ? (n2 == '' ? 0 : 1) : 0;
			return t2 - t1;
		}
	}

	//地图天气展示
	function drawWeatherMap(mapData) {
		var weatherIcons = [];
		var cityBounds = [];
		for (var i = 0, len = mapData.length; i < len; i++) {
			var d = mapData[i];
			var icon = new SuperMap.Feature.Vector(new SuperMap.Geometry.Point(
					d.lon, d.lat), null, {
				externalGraphic : d.gif,
				graphicWidth : 50,
				graphicHeight : 50,
				graphicOpacity : 1,
			});
			icon.data.type = "weather";
			icon.data.value = d;
			// 添加天气图标
			weatherIcons.push(icon);
			// 添加边界
			cityBounds.push(drawWeatherSize(d.boundary));
		}
		weatherLayer.addFeatures(weatherIcons);
		weatherLayer.setVisibility(true);
		selectFeature.activate();
		// 画边界
		affectSizeLayer.addFeatures(cityBounds);
	}

	function showTable() {
		$("#" + divId).css("display", "block");
		PanelTablesUtil.showLoading(divId, "受气象预警影响的设备");
	}

	// 显示分组信息
	function initTable(faultData, secondaryData) {
		var dataset = initTableDataset(faultData);
		var util = new PanelTablesUtil(divId);
		util.setInfo(queryDiv.getComponent);
		if (dataset.length == 0) {
			util.setTitle('受气象预警影响的设备');
			util.setInfo(PanelTablesUtil.getSmileInfo("目前无气象预警。"));
			util.setSuccessBox();
		} else {
			util.setTitle('受气象预警影响的设备');
			util.setDangerBox();
			var myOpt = MyTable.getDefaultOptions();
			myOpt.scrollY = 300;
			myOpt.autoWidth = false;
			myOpt.scrollCollapse = true;
			myOpt.columnDefs = [ {
				"width" : "35%",
				"targets" : 0
			}, {
				"width" : "35%",
				"targets" : 1
			}, {
				"width" : "30%",
				"targets" : 2
			} ];
			for ( var i in dataset) {
				var key = dataset[i].type;
				var value = dataset[i].data;
				var tb = util.drawCollapseTable("weatherEquipmentTable" + key,
						key, false, 'weatherMan.onPanelClick(\'' + key + '\')');
				var tab = new MyTable(
						tb,
						[
								"设备",
								"详细",
								"故障次数<span style='float:right;'><i class='fa fa-question-circle' title='与预警相关故障'/></span>" ],
						myOpt);
				tab.setDataSet(value);
				tab.show();
				tab.onRowClick(function(data) {
					if (data) {
						searchSelectObj(data[0], false, false, data[3]);
					}
				});
			}
			protectUtil.setData(secondaryData);
			util.getCollapsePanelEle("typhoonSecondary", "保护状态评估", false,
					'weatherMan.onPanelClick(\'保护状态评估\')').append(
					protectUtil.getDescDiv()).append(protectUtil.getTableDiv());
		}
		util.show();
	}
	;
	function drawWeatherSize(wbounds) {
		var lrs = [];
		for ( var b in wbounds) {
			var ps = [];
			var bd = wbounds[b];
			for ( var j in bd) {
				var p = new SuperMap.Geometry.Point(bd[j].lng, bd[j].lat);
				ps.push(p);
			}
			var linearRings = new SuperMap.Geometry.LinearRing(ps);
			lrs.push(linearRings);
		}
		var region = new SuperMap.Geometry.Polygon(lrs);
		var bv = new SuperMap.Feature.Vector(region);
		bv.style = {
			strokeColor : "#FA6271",
			strokeType : "dashed",
			fillColor : new SuperMap.Style.RadialGradient(0.5, 0.5, 0.5, 0.5,
					0.5, [ {
						offset : 0.0,
						color : "white",
						opacity : 1
					}, {
						offset : 1.0,
						color : "#FA6271",
						opacity : 0.3
					} ]),// #AAE0B9
			fillOpacity : 0.8
		};

		return bv;
	}

	/*// 设置影响范围，返回范围内受影响的线路及电站
	function getOutBoundsDataSet(type,bounds,cityId) {
	//		var sp = 0.5;
	//		var bounds = new SuperMap.Bounds(points.x-sp,points.y-sp,points.x+sp,points.y+sp);
		
		var dataset = [];
		var datasetLineMap = new Map();//lineid  value:[datasetIndex,杆塔号]
		lineTowerMap = findLineTowerMapByBounds(bounds);
		var lids = [];
		if(lineTowerMap){
			var lns = lineTowerMap.keys;
			var i = 0;
			for(i in lns){
				lids.push(lns[i][0]);
				var tws = lineTowerMap.get(lns[i]);
				dataset.push([lns[i][1],"T"+tws[0]+"---"+"T"+tws[tws.length-1],0,"line",lns[i]]);
				datasetLineMap.put(lns[i][0],[dataset.length-1,tws]);
			}
		}
		idLineIdsMap.put(cityId,lids);
		var stArray = findStationsByBounds(bounds);
		var sids = [];
		if(stArray){
			var i = 0;
			for(i in stArray){
				var st = stArray[i];
				dataset.push([st.name,"",0,"st",st]);
				sids.push(st.id);
			}
		}
		idStationIdsMap.put(cityId, sids);
		getTypeLineFaults(datasetLineMap,dataset,type);
		dataset.splice(0,0,type);// 每个数组的第0个元素为气象类别：线路受哪种气象影响
		return dataset;
	};
	function getTypeLineFaults(datasetLineMap,dataset,type){
		var reasons = getReasons(type);
		for(var i =0;i<lineFaults500.length;i++){
			var fault = lineFaults500[i];
			var faultReason = fault.faultReson;
			var faultLineId = fault.lineCimId;
			if(reasons.indexOf(faultReason) != -1){
				var it = datasetLineMap.get(faultLineId);
				if(it){
					if(it[1].indexOf(""+fault.startPole) != -1){
						dataset[it[0]][2] ++;
					}
				}
			}
		}
	}
	function getReasons(atype){
		var reasons = [];
		if(atype.indexOf("雨") != -1 
				|| atype.indexOf("雷") != -1){
			reasons.push("雷击");
			reasons.push("风偏");
		}else if(atype.indexOf("寒") != -1 
				|| atype.indexOf("冰") != -1
				|| atype.indexOf("冻") != -1
				|| atype.indexOf("雪") != -1){
			reasons.push("覆冰");
		}else if(atype.indexOf("风") != -1 ){// fa-flag-o
			reasons.push("风偏");
		}else if(atype.indexOf("火") != -1){//fa-fire   glyphicon glyphicon-fire
			reasons.push("山火");
		}
		return reasons;
	}
	// 设置影响范围，返回范围内受影响的线路及电站
	function get50kmDataSet(type) {
		var sp = 0.5;
		var bounds = new SuperMap.Bounds(points.x-sp,points.y-sp,points.x+sp,points.y+sp);
		
		var dataset = [];
		dataset.push(type);// 每个数组的第0个元素为气象类别：线路受哪种气象影响
		var lineTowerMap = findLineTowerMapByBounds(bounds);
		if(lineTowerMap){
			var lns = lineTowerMap.keys;
			var i = 0;
			for(i in lns){
				var tws = lineTowerMap.get(lns[i]);
				dataset.push([lns[i][1],"T"+tws[0]+"---"+"T"+tws[tws.length-1],parseInt(Math.random()*10)+"%","line",lns[i]]);
			}
		}
		var stArray = findStationsByBounds(bounds);
		if(stArray){
			var i = 0;
			for(i in stArray){
				var st = stArray[i];
				dataset.push([st.name,"",parseInt(Math.random()*10)+"%","st",st]);
			}
		}
		return dataset;
	};
	// 画圆：气象影响范围
	function createCircle(origin,radius,sides,r,angel){
		var rR = r*Math.PI/(180*sides);
		var rotatedAngle, x, y;
		var points = [];
		for(var i = 0; i < sides; i++){
			rotatedAngle = rR*i;
			x = origin.x + (rad * Math.cos(rotatedAngle));
			y = origin.y + (radius * Math.sin(rotatedAngle));
			points.push(new SuperMap.Geometry.Point(x, y));
		}
		rotatedAngle = r*Math.PI/180;
		x = origin.x + (radius * Math.cos(rotatedAngle));
		y = origin.y + (radius * Math.sin(rotatedAngle));
		points.push(new SuperMap.Geometry.Point(x, y));
		var ring = new SuperMap.Geometry.LinearRing(points);
		ring.rotate(parseFloat(angel),origin);
		var geo = new SuperMap.Geometry.Collection([ring]);
		geo.origin = origin;
		geo.radius = radius;
		geo.r = r;
		geo.angel = angel;
		geo.sides = sides;
		geo.polygonType = "Curve";
		return geo;
	};
	*/
};
